<script setup lang="ts" name="tagSelect">
import { nextTick, ref } from 'vue'
import { ElInput } from 'element-plus'

const props = defineProps<{
  tags: string[]
}>()
// 提交的值
const dynamicTags = ref<string[]>([])
if (props.tags.length > 1) {
  dynamicTags.value = props.tags
}
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

defineExpose({
  dynamicTags
})
</script>

<template>
  <div id="tagAdd">
    <el-tag
      class="tag-element"
      v-for="tag in [...tags, ...dynamicTags].filter((item) => item !== '')"
      :key="tag"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <input
      class="tag-element"
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <button v-else class="tag-element" size="small" @click="showInput">+ 标签</button>
  </div>
</template>

<style scoped>
.tag-element {
  height: 30px;
  color: var(--color2);
  background-color: var(--color1);
  border: 1px solid var(--color2);
  border-radius: var(--radius);
}

#tagAdd {
  width: 200px;
  min-height: 100px;
  margin: 0 auto;
  background-color: var(--color1);
  border: 2px dashed var(--color2);
  border-radius: var(--radius);
  box-sizing: border-box;
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  > span {
    line-height: 30px;
    padding: 0 4px;
  }
  > input {
    text-align: center;
    outline: none;
  }
  > button {
    width: 80px;
  }
}
</style>
